/*
 * @Author: 热的洛夫斯基 501436989@qq.com
 * @Date: 2025-10-05 19:41:17
 * @LastEditors: 热的洛夫斯基 501436989@qq.com
 * @LastEditTime: 2025-10-05 20:18:36
 * @FilePath: /react-0611/src/components/CRUD.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { useState, useEffect } from 'react'
import { Table, Button, Modal, Form } from 'antd';
import { Input } from 'antd';
import { getData } from './asyncdata';
import type { tsDate } from './asyncdata';
import { uuid } from './uuid';
const CrudModel = () => {
    const [dataSource, setDataSource] = useState<tsDate[]>([]);
    const [form] = Form.useForm();
    const [visible, setVisible] = useState(false);
    const showModal = () => {
        setVisible(true);
    };
    const handleCancel = () => {
         form.resetFields();
        setVisible(false);
    };
    const handleOk = () => {
        form?.validateFields().then((values: Partial<tsDate>) => {
            setVisible(false);
            // 为新添加的数据生成唯一ID
            // 确保newData符合tsDate接口
            const newData: tsDate = {
                name: values.name || '',  // 提供默认值确保name不为undefined
                age: values.age || 0,     // 提供默认值确保age不为undefined
                id: uuid(8)
            };
            setDataSource([...dataSource, newData]);
            form.resetFields();
        }).catch(err => {
            console.log(err);
        });
    };
    useEffect(() => {
        getData().then(res => {
            setDataSource(res.data || []);
        });
    }, []);
    return (
        <>


            <Table 
                rowKey="id"
                columns={[
                    {
                        title: '姓名',
                        dataIndex: 'name',
                        key: 'name',
                    },
                    {
                        title: '年龄', 
                        dataIndex: 'age',
                        key: 'age',
                    }
                ]}
                dataSource={dataSource}
            ></Table>

            <Button onClick={showModal}>新增</Button>
            <Modal
                title="新增"
                visible={visible}
                onCancel={handleCancel}
                onOk={handleOk}
            >
                <Form form={form} layout="vertical">
                    <Form.Item name="name" label="姓名" rules={[{ required: true, message: '请输入姓名' }]}>
                        <Input />
                    </Form.Item>
                    <Form.Item name="age" label="年龄" rules={[{ required: true, message: '请输入年龄' }]}>
                        <Input />
                    </Form.Item>
                </Form>
            </Modal>
        </>
    )
}
export default CrudModel
